package info.motteke.qjdbc.exec;

import info.motteke.qjdbc.Statement;
import info.motteke.qjdbc.column.variable.Variable;
import info.motteke.qjdbc.column.variable.VariableInnerAPI;
import info.motteke.qjdbc.exception.SqlException;
import info.motteke.util.Closer;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class BatchStatement<T> implements Statement {

    private final PreparedStatement pstmt;

    private final List<Variable> vars;

    public BatchStatement(PreparedStatement pstmt, List<Variable> vars){
        this.pstmt = pstmt;
        this.vars = vars;
    }

    public void addBatch(){
        try {
            for(int i = 1, length = vars.size(); i < length; i++){
                Variable var = vars.get(i);
                VariableInnerAPI.putValue(var, pstmt, i);
            }
        } catch (SQLException e) {
            Closer.close(pstmt);
            throw new SqlException(e);
        }
    }

    public int[] execute(){
        try{
            return pstmt.executeBatch();
        } catch (SQLException e) {
            throw new SqlException(e);
        } finally {
            Closer.close(pstmt);
        }
    }
}
